package com.xujf.sym.util;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.xujf.sym.App;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class StatusUtil {
	/**
	 * 判断手机是否有sd卡
	 * 
	 * @return
	 */
	public static boolean hasSDCard() {
		String status = Environment.getExternalStorageState();
		return status.equals(Environment.MEDIA_MOUNTED);
	}

	/**
	 * @return 应用程序最大可用内存 ,应用程序已获得内存,应用程序已获得内存中未使用内存
	 */
	public static long[] getMaxMemory() {
		long[] memory = new long[3];
		memory[0] = Runtime.getRuntime().maxMemory() / 1024 / 1024;
		memory[0] = Runtime.getRuntime().totalMemory() / 1024 / 1024;
		memory[0] = Runtime.getRuntime().freeMemory() / 1024 / 1024;
		return memory;
	}

	/**
	 * 获取所有可用RAM大小（GB）
	 * @param context
	 * @return
     */
	public static int getTotalRam(Context context){
		String path = "/proc/meminfo";
		String firstLine = null;
		int totalRam = 0 ;
		try{
			FileReader fileReader = new FileReader(path);
			BufferedReader br = new BufferedReader(fileReader,8192);
			firstLine = br.readLine().split("\\s+")[1];
			br.close();
		}catch (Exception e){
			e.printStackTrace();
		}
		if(firstLine != null){
			totalRam = (int) Math.ceil((new Float(Float.valueOf(firstLine) / (1024 * 1024)).doubleValue()));
		}

		return totalRam;//返回1GB/2GB/3GB/4GB
	}

	/**
	 * 对网络连接状态进行判断
	 *
	 * @return true, 可用； false， 不可用
	 */
	public static boolean isNetworkOpened() {
		ConnectivityManager connManager = (ConnectivityManager) App.Companion.getApplication()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		} else {
			return false;
		}
	}
	/**
	 * 对网络连接状态进行判断
	 *
	 * @return true, 可用； false， 不可用
	 */
	public static boolean isNetworkOpened(Context context) {
		ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connManager.getActiveNetworkInfo() != null) {
			return connManager.getActiveNetworkInfo().isAvailable();
		} else {
			return false;
		}
	}

	/**
	 * 是否连接WIFI
	 *
	 * @param context
	 * @return
     */
	public static boolean isWifiConnected(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		if (wifiNetworkInfo.isConnected()) {
			return true;
		}

		return false;
	}

	/**
	 * 判断某个服务是否正在运行的方法
	 *
	 * @param mContext
	 * @param serviceName
	 *            是包名+服务的类名（例如：com.nozhong.testbackstage.TestService）
	 * @return true代表正在运行，false代表服务没有正在运行
	 */
	public static boolean isServiceWork(Context mContext, String serviceName) {
		boolean isWork = false;
		ActivityManager myAM = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
		List<ActivityManager.RunningServiceInfo> myList = myAM.getRunningServices(50);
		if (myList.size() <= 0) {
			return false;
		}
		for (int i = 0; i < myList.size(); i++) {
			String mName = myList.get(i).service.getClassName().toString();
			if (mName.equals(serviceName)) {
				isWork = true;
				break;
			}
		}
		return isWork;
	}

	/**
	 * 查询手机内非系统应用
	 * 
	 * @param context
	 * @return
	 */
	public static List getAllApps(Context context) {

		List apps = new ArrayList();
		PackageManager pManager = context.getPackageManager();
		// 获取手机内所有应用
		List paklist = pManager.getInstalledPackages(0);
		for (int i = 0; i < paklist.size(); i++) {
			PackageInfo pak = (PackageInfo) paklist.get(i);
			// 判断是否为非系统预装的应用程序
			if ((pak.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
				// customs applications
				apps.add(pak);
			}
		}
		return apps;
	}

	/**
	 * 获取手机ip地址
	 *
	 * @return
	 */
	public static String getPhoneIp() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
						// if (!inetAddress.isLoopbackAddress() && inetAddress
						// instanceof Inet6Address) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (Exception e) {
		}
		return "";
	}

	/**
	 * 获取版本号和版本次数
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionCode(Context context, int type) {

		try {

			PackageInfo pi = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 0);
			if (type == 1) {

				return String.valueOf(pi.versionCode);
			} else {

				return pi.versionName;
			}
		} catch (NameNotFoundException e) {

			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 获取版本名
	 * @param context
	 * @return
     */
	public static String getVersionName(Context context) {
		try {
			String versionName = context.getPackageManager().getPackageInfo("com.xujf.pkwm", 0).versionName;
			return versionName;
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isBackground(Context context) {
		String packageName = "com.bozhong.nurse";
		System.out.println("**********************top packageName:"
				+ packageName);
		ActivityManager activityManager = (ActivityManager) context
				.getSystemService(Context.ACTIVITY_SERVICE);

		List<ActivityManager.RunningTaskInfo> tasksInfo = activityManager.getRunningTasks(1);
		if (tasksInfo.size() > 0) {
			System.out.println("*********************curr packageName:"
					+ tasksInfo.get(0).topActivity.getPackageName());
			// 应用程序位于堆栈的顶层
			if (packageName.equals(tasksInfo.get(0).topActivity
					.getPackageName())) {
				Log.i("前台", "Foreground");
				return false;
			}
		}
		Log.i("后台", "Background");
		return true;
	}

	/**
	 * deviceID的组成为：渠道标志+识别符来源标志+hash后的终端识别符
	 *
	 * 渠道标志为：
	 * 1，andriod（a）
	 *
	 * 识别符来源标志：
	 * 1， IMEI（imei）；
	 * 2， 序列号（sn）；
	 * 3， wifi mac地址（wifi）；
	 * 4， id：随机码。若前面的都取不到时，则随机生成一个随机码，需要缓存。
	 *
	 * @param context
	 * @return
	 */
//	public static String getDeviceId(Context context) {
//		StringBuilder deviceId = new StringBuilder();
//		// 渠道标志
//		deviceId.append("a");
//		try {
//			//IMEI（imei）
//			TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//			String imei = tm.getDeviceId();
//			if (!BaseUtil.isEmpty(imei)) {
//				deviceId.append("imei");
//				deviceId.append(imei);
//				return deviceId.toString();
//			}
//
//			//序列号（sn）
//			String sn = tm.getSimSerialNumber();
//			if (!BaseUtil.isEmpty(sn)) {
//				deviceId.append("sn");
//				deviceId.append(sn);
////				LogUtils.e("getDeviceId : " + deviceId.toString());
//				return deviceId.toString();
//			}
//
//			//wifi mac地址
//			WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//			WifiInfo info = wifi.getConnectionInfo();
//			String wifiMac = info.getMacAddress();
//			if (!BaseUtil.isEmpty(wifiMac) && !"02:00:00:00:00:00".equals(wifiMac) && !"020000000000".equals(wifiMac)) {
//				deviceId.append("mac");
//				deviceId.append(wifiMac);
//				return deviceId.toString();
//			}
//
//			//如果上面都没有， 则生成一个id：随机码
//			String uuid = getUUID(context);
//			if (!BaseUtil.isEmpty(uuid)) {
//				deviceId.append("id");
//				deviceId.append(uuid);
//				return deviceId.toString();
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			deviceId.append("id").append(getUUID(context));
//		}
//
//		return deviceId.toString();
//	}

//	/**
//	 * 得到全局唯一UUID
//	 */
//	public static String getUUID(Context context){
//		String uuid = CacheUtil.getFakeUuid();
//		if(BaseUtil.isEmpty(uuid)){
//			uuid = UUID.randomUUID().toString();
//			CacheUtil.saveFakeUuid(uuid);
//		}
//		LogUtils.e("getUUID : " + uuid);
//
//		return uuid;
//	}

	/**
	 * 获取手机系统信息，如定制系统rom信息等
	 * @param propName
	 * @return
     */
	public static String getSystemProperty(String propName){
		String line = "";
		BufferedReader input = null;
		try {
			Process p = Runtime.getRuntime().exec("getprop " + propName);
			input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024);
			line = input.readLine();
			input.close();
		} catch (IOException ex) {
//			LogUtils.e("Unable to read sysprop " + propName + ex);
			return null;
		} finally {
			if(input != null) {
				try {
					input.close();
				} catch (IOException e) {
//					LogUtils.e("Exception while closing InputStream" + e);
				}
			}
		}
		return line;
	}

	/**
	 * 判断是否为MIUI系统（MIUI系统会绕过权限系统的）
	 * @return
	 */
	public static boolean isMiui() {
		if (BaseUtil.isEmpty(StatusUtil.getSystemProperty("ro.miui.ui.version.name"))) {
			return false;
		}

		return true;
	}

	/**
	 * 判断是否为魅族系统
	 * @return
     */
	public static boolean isFlyme() {
		try {
			// Invoke Build.hasSmartBar()
			final Method method = Build.class.getMethod("hasSmartBar");
			return method != null;
		} catch (final Exception e) {
			return false;
		}
	}

	public static String getNetworkType(Activity activity) {
		String strNetworkType = "";

		NetworkInfo networkInfo = ((ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE))
				.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				strNetworkType = "WiFi";
			}
			else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
				String _strSubTypeName = networkInfo.getSubtypeName();

//				LogUtils.e("Network getSubtypeName : " + _strSubTypeName);

				// TD-SCDMA   networkType is 17
				int networkType = networkInfo.getSubtype();
				switch (networkType) {
					case TelephonyManager.NETWORK_TYPE_GPRS:
					case TelephonyManager.NETWORK_TYPE_EDGE:
					case TelephonyManager.NETWORK_TYPE_CDMA:
					case TelephonyManager.NETWORK_TYPE_1xRTT:
					case TelephonyManager.NETWORK_TYPE_IDEN: //api<8 : replace by 11
						strNetworkType = "2G";
						break;

					case TelephonyManager.NETWORK_TYPE_UMTS:
					case TelephonyManager.NETWORK_TYPE_EVDO_0:
					case TelephonyManager.NETWORK_TYPE_EVDO_A:
					case TelephonyManager.NETWORK_TYPE_HSDPA:
					case TelephonyManager.NETWORK_TYPE_HSUPA:
					case TelephonyManager.NETWORK_TYPE_HSPA:
					case TelephonyManager.NETWORK_TYPE_EVDO_B: //api<9 : replace by 14
					case TelephonyManager.NETWORK_TYPE_EHRPD:  //api<11 : replace by 12
					case TelephonyManager.NETWORK_TYPE_HSPAP:  //api<13 : replace by 15
						strNetworkType = "3G";
						break;

					case TelephonyManager.NETWORK_TYPE_LTE:    //api<11 : replace by 13
						strNetworkType = "4G";
						break;

					default:
						// http://baike.baidu.com/item/TD-SCDMA 中国移动 联通 电信 三种3G制式
						if (_strSubTypeName.equalsIgnoreCase("TD-SCDMA") || _strSubTypeName.equalsIgnoreCase("WCDMA") || _strSubTypeName.equalsIgnoreCase("CDMA2000")) {
							strNetworkType = "3G";
						} else {
							strNetworkType = _strSubTypeName;
						}

						break;
				}
//				LogUtils.e("Network getSubtype : " + Integer.valueOf(networkType).toString());
			}
		}

//		LogUtils.e("Network Type : " + strNetworkType);

		return strNetworkType;
	}

	/**
	 * 获取当前进程名
	 * @param context
	 * @return 进程名
	 */
	public static final String getProcessName(Context context) {
		String processName = null;
		// ActivityManager
		ActivityManager am = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE));
		while (true) {
			for (ActivityManager.RunningAppProcessInfo info : am.getRunningAppProcesses()) {
				if (info.pid == android.os.Process.myPid()) {
					processName = info.processName;

					break;
				}
			}
			// go home
			if (!TextUtils.isEmpty(processName)) {
				return processName;
			}
			// take a rest and again
			try {
				Thread.sleep(100L);
			} catch (InterruptedException ex) {
				ex.printStackTrace();
			}
		}
	}

}
